package m.jclecai.com.fragment;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.squareup.okhttp.Request;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import m.jclecai.com.MyApplication;
import m.jclecai.com.R;
import m.jclecai.com.activity.AboutUSActivity;
import m.jclecai.com.activity.AccountInfoActivity;
import m.jclecai.com.activity.AlterNicknameActivity;
import m.jclecai.com.activity.BalanceActivity;
import m.jclecai.com.activity.BindIDCardActivity;
import m.jclecai.com.activity.BindbankCardActivity;
import m.jclecai.com.activity.InvitedFriendActivity;
import m.jclecai.com.activity.LoginActivity;
import m.jclecai.com.activity.ProductSuggestActivity;
import m.jclecai.com.activity.RechargeActivity;
import m.jclecai.com.activity.RedPkgActivity;
import m.jclecai.com.activity.RedPkgManagerActivity;
import m.jclecai.com.activity.SettingActivity;
import m.jclecai.com.activity.ShowInvitedFriendActivity;
import m.jclecai.com.activity.UserInfoActivity;
import m.jclecai.com.activity.VoteRecordActivity;
import m.jclecai.com.activity.WithdrawActivity;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.BankBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.bean.VersionBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.service.DownloadService;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.AutoSwipeRefreshLayout;
import m.jclecai.com.view.rounded.RoundedImageView;
import rx.functions.Action1;

import static m.jclecai.com.utils.http.SystemUtils.getVersionName;


/**
 * 我的 开关
 */
public class UserSwitchFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.iv_icon)
    RoundedImageView ivIcon;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.tv_onclick_login)
    TextView tvOnclickLogin;
    @BindView(R.id.tv_user_money)
    TextView tvUserMoney;
    @BindView(R.id.tv_redpkg)
    TextView tv_redpkg;
    @BindView(R.id.srl)
    AutoSwipeRefreshLayout srl;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.rl_logout)
    TextView rl_logout;

    UserBean userBean;
    BankBean bankBean;


    @BindView(R.id.tv_nickname)
    TextView mTvNickname;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_user_test;
    }

    @Override
    public void initData() {
        userBean = PreferenceUtil.readUser(getActivity());
        bankBean = PreferenceUtil.getDefaultWithDrawBank(getActivity());

        if (bankBean == null && userBean != null) {
            //这里表示如果本地没有默认的银行卡的话，使用UserBean中的
            bankBean=userBean.createBankBean();
        }

        srl.setOnRefreshListener(this);
        srl.setRefreshing(true);
        updateText();
        getUserInfo();

    }




    void getUserInfo() {
//        showDialog();
        String userName = PreferenceUtil.getUserName(getActivity());
        String password = PreferenceUtil.getPassword(getActivity());
        HashMap<String, String> pair = new HashMap<>();
        pair.put("user", userName);
        pair.put("password", password);
        Constant_Url.HTTP_URL = MyApplication.HTTP_URL;
        HttpManager.postAsyn(Constant_Url.GET_USER_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                if (srl != null)
                    srl.setRefreshing(false);
            }

            @Override
            public void onResponse(String response) {
                if (srl != null)
                    srl.setRefreshing(false);
                dissDialog();
                UserBean usb = FastOk.get(response, UserBean.class);
                if (usb == null) {
                    DisPlay(setString(R.string.error_network));
                    rl_logout.setVisibility(View.GONE);
                    return;
                }
                userBean = usb;
                if ("1011".equals(usb.getStatus())) {//未登录返回首页 ios 逻辑
                    userBean = null;
                    rl_logout.setVisibility(View.GONE);
                }else{
                    rl_logout.setVisibility(View.VISIBLE);
                }
                if (getActivity() == null) {
                    return;
                }
                PreferenceUtil.writeUser(getActivity(), userBean);
                updateText();
            }
        }, pair);
    }

    @Override
    public void onResume() {
        super.onResume();
        userBean = PreferenceUtil.readUser(getActivity());
        bankBean = PreferenceUtil.getDefaultWithDrawBank(getActivity());
        if (bankBean == null && userBean != null) {
            //如果银行为空，设置一个默认的；
            bankBean=userBean.createBankBean();
            PreferenceUtil.setDefaultWithDrawBank(getActivity(),bankBean);
        }
        getUserInfo();
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //如果未登录则显示首页
        if (Constant_Result.SHOWUSERFRAGMENT == requestCode && resultCode != FragmentActivity.RESULT_OK) {
//            ((MainTestActivity) getActivity()).selectHomeTab();
        } else if (Constant_Result.CLEARALLUSERDATA == requestCode && resultCode == FragmentActivity.RESULT_OK) {
            //如果清除登录信息则调用登录
            startActivityForResult(new Intent(getActivity(), LoginActivity.class), Constant_Result.SHOWUSERFRAGMENT);
        } else if (Constant_Result.BINDBANK == requestCode && resultCode == FragmentActivity.RESULT_OK) {
            //点击提现
            startActivity(new Intent(getActivity(), WithdrawActivity.class));
        } else if (Constant_Result.BINDCARD == requestCode && resultCode == FragmentActivity.RESULT_OK) {
            //如果没有绑定银行卡 先去绑定银行卡
            if (bankBean == null) {
                startActivityForResult(new Intent(getActivity(), BindbankCardActivity.class),
                        Constant_Result.BINDBANK);
                return;
            } else {
                //点击提现
                startActivity(new Intent(getActivity(), WithdrawActivity.class));
            }
        }
    }

    @OnClick({R.id.rl_user, R.id.tv_name, R.id.iv_icon, R.id.rl_pinformation, R.id.rl_hongbao,
            R.id.rl_hongbao_manager, R.id.rl_chongzhi, R.id.rl_tixian, R.id.rl_touzhu,
            R.id.rl_zhuihao, R.id.rl_shezhi, R.id.rl_hemai,R.id.rl_user_nickname,R.id.ll_tui_guang,
            R.id.rl_version, R.id.rl_suggest,
            R.id.rl_invite, R.id.rl_about, R.id.rl_logout})
    public void onClick(View view) {
        srl.setRefreshing(false);
        if (!isLogin() || userBean == null) {
            startActivityForResult(new Intent(getActivity(), LoginActivity.class),
                    Constant_Result.SHOWUSERFRAGMENT);
            return;
        }
        switch (view.getId()) {
            case R.id.iv_icon:
            case R.id.tv_name:
                startActivity(new Intent(getActivity(), UserInfoActivity.class));
                break;
            case R.id.rl_user:
                startActivityForResult(new Intent(getActivity(), AccountInfoActivity.class),
                        Constant_Result.CLEARALLUSERDATA);
                break;
            case R.id.rl_pinformation:
                //点击账户余额
                //判断是否登录
                BaseUtils.startAcy(getActivity(), BalanceActivity.class);
                break;
            case R.id.rl_hongbao:
                //点击红包,先判断是否登录
                BaseUtils.startAcy(getActivity(), RedPkgActivity.class);
                break;
            case R.id.rl_hongbao_manager:
                //点击红包,先判断是否登录
                BaseUtils.startAcy(getActivity(), RedPkgManagerActivity.class);
                break;
            case R.id.rl_chongzhi:
                //点击充值
                BaseUtils.startAcy(getActivity(), RechargeActivity.class);
                break;
            case R.id.rl_tixian:
                //如果没有绑定身份证，先去绑定身份证
                if (TextUtils.isEmpty(userBean.getIdcard())) {
                    startActivityForResult(new Intent(getActivity(), BindIDCardActivity.class),
                            Constant_Result.BINDCARD);
                    return;
                }
                //如果没有绑定银行卡 先去绑定银行卡
               /* if (bankBean == null) {
                    startActivityForResult(new Intent(getActivity(), BindbankCardActivity.class),
                            Constant_Result.BINDBANK);
                    return;
                }*/
                //点击提现
                startActivity(new Intent(getActivity(), WithdrawActivity.class));
                break;
            case R.id.rl_touzhu:
                //点击投注
                startActivity(new Intent(getActivity(), VoteRecordActivity.class)
                        .putExtra("index", 0)
                        .putExtra("title", "购买记录"));
                break;
            case R.id.rl_zhuihao:
                //点击追号
                startActivity(new Intent(getActivity(), VoteRecordActivity.class)
                        .putExtra("index", 1)
                        .putExtra("title", "追号记录"));
                break;
            case R.id.rl_shezhi:
                //点击设置
                startActivityForResult(new Intent(getActivity(), SettingActivity.class),
                        Constant_Result.CLEARALLUSERDATA);
                break;
            case R.id.rl_hemai:
                //点击合买
                startActivity(new Intent(getActivity(), VoteRecordActivity.class)
                        .putExtra("index", 2)
                        .putExtra("title", "合买记录"));
                break;
            case R.id.rl_user_nickname:
                startActivity(new Intent(getActivity(),AlterNicknameActivity.class));
                break;
            case R.id.ll_tui_guang:
                startActivity(new Intent(getActivity(), ShowInvitedFriendActivity.class));
                break;

            case R.id.rl_version:
                //检查版本；
                checkVersion();
                break;
            case R.id.rl_suggest:
                startActivity(new Intent(getActivity(),ProductSuggestActivity.class));
                break;
            case R.id.rl_invite:
                //邀请别人
                checkLogin(new Callback() {
                    @Override
                    public void callbackSuccess() {
                        super.callbackSuccess();
                        startActivity(new Intent(getActivity(),
                                InvitedFriendActivity.class));
                    }
                });
                break;
            case R.id.rl_about:
                //关于我们；
                startActivity(new Intent(getActivity(),AboutUSActivity.class));
                break;
            case R.id.rl_logout:
                //登出
                logout();
                break;
        }
    }

    void updateText() {
        //safe 2 - 中
        tvOnclickLogin.setText("");
        tvLogin.setText("未登录");
        tvUserMoney.setText(("0.00元"));
        tv_redpkg.setText(("0.00元"));
        ivIcon.setImageResource(R.drawable.my_head_de);
        tvName.setText("未登录");
        if (userBean != null && isLogin()) {

            Glide.with(this)
                    .load(userBean.getUser_face())
                    .asBitmap()
                    .placeholder(R.drawable.my_head_de)
                    .error(R.drawable.my_head_de)
                    .into(ivIcon);

            String name = TextUtils.isEmpty(userBean.getUsername()) ? userBean.getPhone() : userBean.getUsername();
            tvName.setText(name);
            tv_redpkg.setText((userBean.getRedpacketmoney() + "元"));
            tvUserMoney.setText((userBean.getAllmoney() + "元"));
            tvLogin.setText(name);
            String level = "低";
            if ("2".equals(userBean.getSafe()) || "3".equals(userBean.getSafe()))
                level = "中";
            else if ("1".equals(userBean.getSafe()))
                level = "高";
            tvOnclickLogin.setText(("安全等级:" + level));

            //这里设置用户名；

            if(!TextUtils.isEmpty(userBean.getNickname())){
                mTvNickname.setText(userBean.getNickname());
            }
        }
    }


    /**
     *  设置相关
     */
    /**
     * 请求服务器，来检查本地的版本和服务器是否一样；
     */
    private void checkVersion() {
        //1、获取本地版本信息；
        //2、请求服务器是否更新；
        //3、弹出对话框显示新版本特性；
        //4、启动Services;

        final String versionCode = getVersionCode();
        final String versionName = getVersionName();

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        final View view = View.inflate(getActivity(), R.layout.dialog_update_layout, null);
        builder.setView(view);

        DisPlay("检查版本中...");
        HttpManager.getAsyn(Constant_Url.GET_LATEST + "?version=" + versionName + "&type=android" + "&versionCode=" + versionCode+"&appstore="+ ChannelUtil.getChannel(), new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                //请检查网络；
                DisPlay("请检查网络...");
            }

            @Override
            public void onResponse(String response) {
                //判断返回结果：
                final VersionBean versionBean = FastOk.get(response, VersionBean.class);
                if (versionBean.getStatus().equals("1")) {

                    try{
                        //服务器返回的数据有问题
                        final AlertDialog alertDialog = builder.create();
                        RxPermissions rxPermissions = new RxPermissions(getActivity());
                        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                .subscribe(new Action1<Boolean>() {
                                    @Override
                                    public void call(Boolean aBoolean) {
                                        if (aBoolean) {
                                            alertDialog.show();
                                        }else{
                                            DisPlay("获取权限失败！！！");
                                        }
                                    }
                                });


                        view.findViewById(R.id.tv_update).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //这里我们要做的一个操作就是升级；
                                Intent intent = new Intent(getActivity(), DownloadService.class);

                                long apkSize = 0;

                                try {
                                    apkSize=Long.parseLong(versionBean.getApkSize());
                                } catch (NumberFormatException e) {
                                    e.printStackTrace();
                                }

                                intent.putExtra(DownloadService.APK_SIZE,apkSize);

                                intent.putExtra(DownloadService.DOWNLOAD_URL,versionBean.getDownload());
                                getActivity().startService(intent);
                                alertDialog.dismiss();
                            }
                        });
                        //这里表示需要更新；在这里写的话可以偷懒
                        view.findViewById(R.id.tv_no_update).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                alertDialog.dismiss();
                            }
                        });

                        String  content="版本:"+versionBean.getVersion()+"\n";

                        float v = Float.parseFloat(versionBean.getApkSize()) / 1024 / 1024;
                        //保留两位小数
                        content+="包大小:"+(float)(Math.round(v*100))/100+"m\n\n";


                        String[] split = versionBean.getContent().split(";");
                        content+="更新内容：\n";
                        for(int i=0;i<split.length;i++){
                            content+=split[i]+"。\n";
                        }
                        content+="升级的小伙伴,今天晚上更容易中大奖哦。";
                        ((TextView) view.findViewById(R.id.tv_content)).setText(content);

                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    DisPlay("你已经是最新版了");
                }
            }
        });

    }

    /**
     * 这里我们获取版本号；
     * @return
     */
    private String getVersionCode() {

        PackageManager packageManager = getActivity().getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
            int versionCode = packageInfo.versionCode;
            return versionCode+"";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return "";
    }

    void logout() {
        showDialog();
        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
        if (platform.isAuthValid()) {
            platform.removeAccount(true);
        }

        PreferenceUtil.clearUserInfo(getActivity());
        PreferenceUtil.writeBoolean(getActivity(),PreferenceUtil.WEI_XIN_IS_BIND_PHONE_NUMBER,true);//这里微信登陆绑定了手机号码；
        PreferenceUtil.writeBoolean(getActivity(),PreferenceUtil.IS_USER_NAME_EMPTY,false);//这里微信登陆绑定了手机号码；

        HttpManager.getAsyn(Constant_Url.LOGOUT, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                getUserInfo();
            }
        });
    }


    @Override
    public void onRefresh() {
        getUserInfo();
    }
}
